package com.qf.servlet;

import com.qf.entity.Admin;
import com.qf.util.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * description: 注册servlet
 * author: Ken
 * 公众号：Java架构栈
 */
@WebServlet(urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {

    /**
     * 用来处理任何类型的请求 POST、GET、PUT....
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
    }

    /**
     * Servlet专门用来处理post请求的方法
     *
     * 注册管理员
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //post请求乱码的处理
        req.setCharacterEncoding("utf-8");
        //接收注册的请求
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String againpassword = req.getParameter("againpassword");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String[] powers = req.getParameterValues("power");
        String jiguan = req.getParameter("jiguan");

        System.out.println(username + " " + password + " " + againpassword + " " + name
                + " " + sex + " " + birthday + " " + Arrays.toString(powers) + " " + jiguan);

        //参数校验
        if (password == null || password.equals("") || !password.equals(againpassword)) {
            //密码输入有问题
            //1 - 两次密码输入异常
            resp.sendRedirect("register.jsp?status=1");
            return;
        }

        if (username == null || username.equals("")) {
            //用户名不能为null
            //2 - 用户名不能为空
            resp.sendRedirect("register.jsp?status=2");
            return;
        }

        //将注册信息 转换成 实体类
        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setPassword(password);
        admin.setName(name);
        admin.setSex(sex);
        admin.setBirthday(birthday);
        admin.setPowers(powers);
        admin.setJiguan(jiguan);

        //存储用户的注册信息 - 存储到数据库 - List集合中
        DataUtils.addAdmin(admin);
        //注册成功！-- 跳转到登录页
        resp.sendRedirect("login.jsp");
    }
}
